package test.test02.MyThread;

public class ThreadSafety {
    public static void main(String[] args) {
        // test01();
        test02();
    }
    static int count = 0;
    public static void test01(){
        Thread t1 = new Thread(()->{
            System.out.println("t1开始");
            for(int i = 0;i < 10000;i++){
                count++;
            }
            System.out.println("t1结束");
        });
        Thread t2 = new Thread(()->{
            System.out.println("t2开始");
            for(int i = 0;i < 10000;i++){
                count++; 
            }
            System.out.println("t2结束");
        });

        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(count);
    }
    public static void test02(){
        count = 0;
        Object locker = new Object();//创建锁

        Thread t1 = new Thread(()->{
            System.out.println("t1开始");
            for(int i = 0;i < 10000;i++){
                // 加锁
                synchronized(locker){
                    count++;
                }
            }
            System.out.println("t1结束");
        });
        Thread t2 = new Thread(()->{
            System.out.println("t2开始");
            for(int i = 0;i < 10000;i++){
                // 加锁
                synchronized(locker){
                    count++;
                }
            }
            System.out.println("t2结束");
        });

        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(count);
    }
}
